#include "common.h"

/* Create socket and connect to server. */

void create_socket_connect(char* ip, char* port, int* fd){

	struct sockaddr_in sa;

	memset(&sa, 0, sizeof(sa));
	sa.sin_family      = AF_INET;
	inet_pton(sa.sin_family, ip, &(sa.sin_addr));
	sa.sin_port        = htons(atoi(port));
	printf("Hello %d\n", *fd);
	if ( (*fd = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) {
		fprintf(stderr, "ECHOSERV: Error creating sending socket.\n");
		exit(EXIT_FAILURE);
	}
	printf("Hello\n");
	if (connect(*fd, (struct sockaddr *) &sa, sizeof(sa)) < 0)
	{
		perror("ERROR on connecting");
		exit(1);
	}
	printf("Connection with server successfull!\n");

}

/*  Read a line from a socket  */

ssize_t Readline(int sockd, void *vptr, size_t maxlen) {
	ssize_t n, rc;
	char    c, *buffer;

	buffer = vptr;

	for ( n = 1; n < maxlen; n++ ) {

		if ( (rc = read(sockd, &c, 1)) == 1 ) {
			*buffer++ = c;
			if ( c == '\n' )
				break;
		}
		else if ( rc == 0 ) {
			if ( n == 1 )
				return 0;
			else
				break;
		}
		else {
			if ( errno == EINTR )
				continue;
			return -1;
		}
	}

	*buffer = 0;
	return n;
}


/*  Write a line to a socket  */

ssize_t Sendline(int sockd, const void *vptr, size_t n) {
	size_t      nleft;
	ssize_t     nwritten;
	const char *buffer;

	buffer = vptr;
	nleft  = n;

	while ( nleft > 0 ) {
		if ( (nwritten = write(sockd, buffer, nleft)) <= 0 ) {
			if ( errno == EINTR )
				nwritten = 0;
			else
				return -1;
		}
		nleft  -= nwritten;
		buffer += nwritten;
	}

	return n;
}

/* Returns the minimum of 2 size_ts */

size_t minChar (int i, int j) {
	if (i<j) return (size_t)i;
	else return (size_t)j;
}

